package com.example.myapplicationfinalwork.ui.map;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.example.myapplicationfinalwork.MainActivity;
import com.example.myapplicationfinalwork.databinding.FragmentMapBinding;
import com.example.myapplicationfinalwork.model.MapViewModel;
import com.example.myapplicationfinalwork.util.BaiduApplication;

public class MapFragment extends Fragment {
    private String TAG="MapFragment";
    private MapViewModel mapViewModel;
    private FragmentMapBinding binding;
    private MapView mMapView = null;
    private BaiduMap mbaiduMap=null;
    private LocationClient locationClient;
    private boolean flag;
    private boolean ok=true;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mapViewModel =
                new ViewModelProvider(getActivity(),new ViewModelProvider.NewInstanceFactory()).get(MapViewModel.class);

        binding = FragmentMapBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView textView = binding.textHome;
        mapViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });

        flag=((MainActivity)getActivity()).flag;

        mMapView=binding.bmapView;
        mbaiduMap=mMapView.getMap();
        initLocation();

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();

        locationClient.stop();
        mbaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();

    }

    void initLocation(){
        mbaiduMap.setMyLocationEnabled(true);
        locationClient=new LocationClient(getContext());
        MyLocationListener listener=new MyLocationListener();
        locationClient.registerLocationListener(listener);
        LocationClientOption option=new LocationClientOption();

        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);

        locationClient.setLocOption(option);
        locationClient.start();
    }

    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // MapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())// 设置定位数据的精度信息，单位：米
                    .direction(location.getDirection()) // 此处设置开发者获取到的方向信息，顺时针0-360
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            // 设置定位数据, 只有先允许位图层后设置数据才会生效定
            mbaiduMap.setMyLocationData(locData);
            if (flag) {
                flag = false;
                ((MainActivity)getActivity()).flag=false;
                ok=false;
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(latLng).zoom(20.0f);
                mbaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                Log.i(TAG, "onReceiveLocation: "+location.getAddrStr());
                mapViewModel.setCity(location.getCity());
                ((MainActivity)getActivity()).localedCity=location.getCity();
                Toast.makeText(getContext(), location.getAddrStr(), Toast.LENGTH_SHORT).show();
            }
            else if(ok){
                ok=false;
                GeoCoder geoCoder=GeoCoder.newInstance();//根据某个key寻找地理位置的坐标，这个key可以是地址还可以是ip地址
                // 得到GenCodeOption对象
                GeoCodeOption geoCodeOption=new GeoCodeOption();//地理编码请求参数
                String address=((MainActivity)getActivity()).localedCity;
                geoCodeOption.address(address);
                geoCodeOption.city(address); // 这里必须设置城市，否则会报错
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    //将具体的地址转化为坐标
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                        if (geoCodeResult==null||geoCodeResult.error!= SearchResult.ERRORNO.NO_ERROR){
                            Toast.makeText(getContext(),"检索错误",Toast.LENGTH_SHORT).show();
                        }else {
                            // 得到具体地址的坐标
                            //LatLng是存储经纬度坐标值的类，单位角度。
                            LatLng latLng=geoCodeResult.getLocation();//使用传入的经纬度构造LatLng 对象，一对经纬度值代表地球上一个地点。
                            // 设置地图跳转的参数
                            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory
                                    .newLatLngZoom(latLng, 13);
                            // 设置进行地图跳转
                            mbaiduMap.setMapStatus(mMapStatusUpdate);

                        }
                    }
                    // 这个方法是将坐标转化为具体地址
                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

                    }
                });

                // 这句话必须写，否则监听事件里面的都不会执行
                geoCoder.geocode(geoCodeOption);
            }
        }
    }
}

